package com.yc.damai.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.damai.entity.Product;
import com.yc.damai.mapper.ProductMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("ms")
public class MsAction {

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    ProductMapper productMapper;

    private boolean begined;

    @RequestMapping("begin")
    public String begin(){
        // 对热卖商品参与秒杀
        LambdaQueryWrapper<Product> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Product::getIsHot,1);
        List<Product> products = productMapper.selectList(lqw);
        // 将库存数保存到 redis
        products.forEach(p->{
            redisTemplate.opsForHash().put("msProducts",
                    p.getPid(), p.getNums());
        });
        begined = true;
        return "秒杀活动开始!";
    }

    @RequestMapping("end")
    public String end(){
        // TODO 秒杀结束之后, 将商品数量更新到 mysql
        begined = false;
        return "秒杀活动结束!";
    }

    // 秒杀方法  => MQ 生产者
    @RequestMapping("commit")
    public String commit(int uid, int pid, int number){
        if(begined==false){
            return "秒杀活动还未开始";
        }
        Object nums = redisTemplate.opsForHash().get("msProducts", pid);
        if(nums == null || (int)nums < number){
            return "商品数量不足!";
        }
        nums = (int)nums - number;
        redisTemplate.opsForHash().put("msProducts",
                pid, nums);
        // 将订单信息发送给消息队列
        OrderInfo orderInfo = new OrderInfo(uid,pid,number);
        rabbitTemplate.convertAndSend("msOrderQueue", orderInfo);
        return "订单已经受理, 请静候佳音!";
    }

    // 订单方法  => MQ 消费者
    @RabbitListener(queuesToDeclare = @Queue("msOrderQueue"))
    public void addOrder(OrderInfo info){
        // TODO 保存订单, 请扩展完成
        System.out.println(info);
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class OrderInfo implements java.io.Serializable{
    int uid, pid, number;
}
